package com.windoent.yugioh.ui.fragment.saishi.end;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.RuiShiLunRankListAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.RuiShiLunListData;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.SimpleUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.RoundImageView;
import com.windoent.yugioh.widget.popupwindow.RuiShiLunFilterPopUpWindow;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/21 11:39
 * desc   :瑞士轮排行
 */
public class EndedRuiShiLunFragment extends BaseFragment {
    private TextView mTvNumbers;
    private RoundImageView mIvAvatar;
    private TextView mTvName;
    private TextView mTvRank;
    private TextView mTvPoints;
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private LinearLayout mLlBottom;

    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private RuiShiLunRankListAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_saishi_ended_ruishilun_rank;
    }

    public static EndedRuiShiLunFragment newsInstance(String id) {
        //创建 Bundle
        EndedRuiShiLunFragment fragment = new EndedRuiShiLunFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("id", id);
        fragment.setArguments(lBundle);
        return fragment;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
    }

    private void initData() {
        initAdapter();
    }

    private void initView() {

        mTvNumbers = (TextView) mView.findViewById(R.id.tv_numbers);
        mIvAvatar = (RoundImageView) mView.findViewById(R.id.iv_avatar);
        mTvName = (TextView) mView.findViewById(R.id.tv_name);
        mTvRank = (TextView) mView.findViewById(R.id.tv_rank);
        mTvPoints = (TextView) mView.findViewById(R.id.tv_points);
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mLlBottom = (LinearLayout) mView.findViewById(R.id.ll_bottom);
    }

    private void initRefreshData(String text) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(text);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                loadMore(text);
            }
        });
    }

    private void loadMore(String text) {
        mCount = mCount + 1;
        getRuiShiLunlist(text, mCount + "", limit, false);
    }

    private void fresh(String text) {
        mCount = 1;
        getRuiShiLunlist(text, mCount + "", limit, true);
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new RuiShiLunRankListAdapter();
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty_ruishilun, mRecyclerView, false));
        adapter.setAnimationEnable(false);
        mRecyclerView.setAdapter(adapter);
    }

    //筛选
    private void addFirstHeader(RuiShiLunRankListAdapter adapter, List<RuiShiLunListData.DataBean.FilterBean> filter, RuiShiLunListData.DataBean.SelectFilterBean selectFilter) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_ruishilun_rank_select, (ViewGroup) mRecyclerView.getParent(), false);
            TextView tv_name_select = headView.findViewById(R.id.tv_name_select);
            tv_name_select.setText(BaseMethod.notNullDefaultValue(selectFilter.getTitle(), getString(R.string.string_select_luns_filter_warning)));
            RelativeLayout rl_select = headView.findViewById(R.id.rl_select);
            rl_select.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showPopSelectCaiPan(filter, rl_select);
                }
            });
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
                if (adapter.hasEmptyView()) {
                    adapter.setUseEmpty(false);
                }
            }
        }
    }

    //筛选轮数
    private void showPopSelectCaiPan(List<RuiShiLunListData.DataBean.FilterBean> filter, RelativeLayout mLlSelectCaipan) {
        if (filter != null) {
            new RuiShiLunFilterPopUpWindow(mContext, filter, new RuiShiLunFilterPopUpWindow.OnInterface() {
                @Override
                public void onSelect(RuiShiLunListData.DataBean.FilterBean filterBean) {
                    String round = filterBean.getRounds() + "";
                    initRefreshData(round);
                    fresh(round);
                }
            }).showAtBottom(mLlSelectCaipan, 0, 0);
        } else ToastUtils.showText(getString(R.string.string_no_data));
    }

    //标题
    private void addSecondHeader(RuiShiLunRankListAdapter adapter) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_ruishilun_rank_title, (ViewGroup) mRecyclerView.getParent(), false);
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
                if (adapter.hasEmptyView()) {
                    adapter.setUseEmpty(false);
                }
            }
        }
    }

    //yuan标题
    private void addSecondConorHeader(RuiShiLunRankListAdapter adapter) {
        if (isAdded() && getActivity() != null) {
            View headView = getLayoutInflater().inflate(R.layout.head_rv_view_ruishilun_rank_conor_title, (ViewGroup) mRecyclerView.getParent(), false);
            if (adapter != null) {
                adapter.addHeaderView(headView);
                adapter.setHeaderWithEmptyEnable(true);
                if (adapter.hasEmptyView()) {
                    adapter.setUseEmpty(false);
                }
            }
        }
    }

    //列表
    private void getRuiShiLunlist(String title, String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getRuiShiLunList(getUserToken(), id, title, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            RuiShiLunListData json = gson.fromJson(response, RuiShiLunListData.class);
                            if (json != null) {
                                RuiShiLunListData.DataBean data = json.getData();
                                if (data != null) {
                                    List<RuiShiLunListData.DataBean.CurrentUserBean> againstResultSwiss = data.getAgainstResultSwiss();
                                    RuiShiLunListData.DataBean.CurrentUserBean currentUser = data.getCurrentUser();
                                    List<RuiShiLunListData.DataBean.FilterBean> filter = data.getFilter();
                                    RuiShiLunListData.DataBean.SelectFilterBean selectFilter = data.getSelectFilter();
                                    if (adapter != null && adapter.getHeaderLayoutCount() > 0) {
                                        adapter.removeAllHeaderView();
                                    }
                                    if (againstResultSwiss != null && againstResultSwiss.size() > 0) {
                                        if (filter != null && selectFilter != null) {
                                            addFirstHeader(adapter, filter, selectFilter);
                                            addSecondHeader(adapter);
                                        } else addSecondConorHeader(adapter);
                                    }
                                    mLlBottom.setVisibility(currentUser == null || currentUser.getRank() == 0 ? View.GONE : View.VISIBLE);
                                    if (currentUser != null) {
                                        setUserInfo(currentUser);
                                    }
                                    if (againstResultSwiss != null) {
                                        if (fresh) {
                                            adapter.setNewInstance(againstResultSwiss);
                                            mSmartLayout.finishRefresh(true);
                                        } else {
                                            adapter.addData(againstResultSwiss);
                                            adapter.notifyDataSetChanged();
                                            mSmartLayout.finishLoadMore(true);
                                        }
                                    } else freshFail(fresh);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //底部自己信息
    private void setUserInfo(RuiShiLunListData.DataBean.CurrentUserBean currentUser) {
        SimpleUtils.loadImageForView(mContext, mIvAvatar, currentUser.getAvatar(), R.drawable.img_official_avatar_android);
        setText(mTvNumbers, currentUser.getRank() + "");
        setText(mTvName, currentUser.getNickname());
        setText(mTvRank, currentUser.getScore() + "");
        setText(mTvPoints, currentUser.getTiebreaker() + "");
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事进行中瑞士轮tab");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事进行中瑞士轮tab");
        }
        getDetailsId();
    }

    private String id;

    //获取activity传值id
    private void getDetailsId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString("id");
            initRefreshData("");
            fresh("");
        }
    }
}
